package com.local.localRestful.repository;

import com.local.localRestful.domain.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * {@link User} {@link Repository}
 * Created by zzy on 2018/1/14.
 * 采用内存
 */
@Repository
public class UserRepository {

    private ConcurrentMap<Integer,User> repository=new ConcurrentHashMap();

    private final static AtomicInteger  idGenerator=new AtomicInteger();

    /**
     * 保存用户对象
     * @param user {@link User}
     * @return 如果保存成功，返回<code>true</code>
     *          否则，返回<code>false</code>
     */
    public boolean save(User user){
        Integer id=idGenerator.incrementAndGet();
        user.setId(id);
        return repository.put(id,user)==null;
    }

    public List<User> findAll(){
        List<User> result=new ArrayList();
        for(Map.Entry<Integer,User> entry:repository.entrySet()){
            result.add(entry.getValue());
        }
        return result;
    }
}
